package com.yuebook.smartrpc.framework.serialization;

import com.yuebook.smartrpc.framework.serialization.common.SerializerType;
import com.yuebook.smartrpc.framework.serialization.engine.SerializerEngine;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author honglei
 * @date 2018/11/19 下午9:29
 */
public class NettyEncodeHandler extends MessageToByteEncoder {

    private SerializerType serializerType;

    public NettyEncodeHandler(SerializerType serializerType) {
        this.serializerType = serializerType;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        byte[] bytes = SerializerEngine.serialize(o, serializerType.getDisplayName());
        byteBuf.writeInt(bytes.length);//写入字节数目
        byteBuf.writeBytes(bytes);
    }
}
